package site.zbox.tool.swing.xml;

import java.awt.Dimension;
import java.awt.Insets;

import site.zbox.tool.lang.NumberUtils;
import site.zbox.tool.lang.StringUtils;
import site.zbox.tool.lang.Version;

@Version("2021.08.18")
public class ParserUtils {
    public static AttributeValueMap newAttributeValueMap(String attributeValue) {
        final AttributeValueMap map = new AttributeValueMap();
        attributeValue = StringUtils.stripToEmpty(attributeValue);
        if (StringUtils.isEmpty(attributeValue)) {
            return map;
        }
        for (String entry : StringUtils.split(attributeValue, ';')) {
            final String[] array = StringUtils.split(entry, ':');
            if (array.length != 2) {
                continue;
            }
            final String key = StringUtils.stripToEmpty(array[0]);
            final String value = StringUtils.stripToEmpty(array[1]);
            if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
                continue;
            }
            map.put(key, value);
        }
        return map;
    }

    public static Dimension newDimension(final String value) {
        final String[] split = StringUtils.split(value, ',');
        int width = 0;
        int height = 0;
        if (split.length > 0) {
            width = NumberUtils.toInt(StringUtils.trimToEmpty(split[0]));
            height = width;
        }
        if (split.length > 1) {
            height = NumberUtils.toInt(StringUtils.trimToEmpty(split[1]));
        }
        return new Dimension(width, height);
    }

    public static Insets newInsets(final String value) {
        final String[] split = StringUtils.split(value, ',');
        int top = 0;
        int left = 0;
        int bottom = 0;
        int right = 0;
        if (split.length >= 4) {
            top = NumberUtils.toInt(StringUtils.trimToEmpty(split[0]), 1);
            left = NumberUtils.toInt(StringUtils.trimToEmpty(split[1]), 1);
            bottom = NumberUtils.toInt(StringUtils.trimToEmpty(split[2]), 1);
            right = NumberUtils.toInt(StringUtils.trimToEmpty(split[3]), 1);
        } else if (split.length >= 2) {
            top = NumberUtils.toInt(StringUtils.trimToEmpty(split[0]), 1);
            left = NumberUtils.toInt(StringUtils.trimToEmpty(split[1]), 1);
            bottom = top;
            right = left;
        } else if (split.length >= 1) {
            top = NumberUtils.toInt(StringUtils.trimToEmpty(split[0]), 1);
            left = top;
            bottom = top;
            right = top;
        }
        return new Insets(top, left, bottom, right);
    }

    public ParserUtils() {
        super();
    }
}
